<!---->
<template>
	<view class="container">
		<!-- 自定义顶部栏（替代原生导航栏） -->
		<view class="custom-nav-bar">
			<view class="title-container">
				<text class="title">自主绘画</text>
				<text class="subtitle">智引未来</text>
			</view>
		</view>


		<!-- 提示文字 -->
		<view class="tip">
			<u-icon name="warning" size="32" color="#f9ae3d" style="margin-right: 10rpx;"></u-icon>
			<text>请用户绘画一个房子</text>
		</view>

		<!-- 绘画区域 -->
		<view class="drawing-area">
			<canvas canvas-id="drawingCanvas" class="drawing-canvas" disable-scroll="true"
				@touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd"></canvas>
		</view>

		<!-- 工具栏 -->
		<view class="toolbar">
			<view class="color-picker">
				<view v-for="color in colors" :key="color" class="color-option"
					:style="{backgroundColor: color, border: selectedColor === color ? '2rpx solid #1296db' : '2rpx solid #e4e7ed'}"
					@click="selectColor(color)"></view>
			</view>
			<view class="brush-size">
				<text>画笔大小: {{brushSize}}</text>
				<slider :value="brushSize" min="1" max="20" step="1" activeColor="#1296db"
					@change="handleSliderChange" />
			</view>
		</view>

		<!-- 操作按钮 -->
		<view class="action-buttons">
			<u-button type="primary" shape="circle" @click="clearCanvas" class="clear-btn">
				清空画布
			</u-button>
			<view class="button-gap"></view>
			<u-button type="success" shape="circle" @click="submitDrawing" class="submit-btn">
				提交
			</u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				colors: [
					'#000000', '#333333', '#666666', '#999999', '#CCCCCC',
					'#FF0000', '#FF6600', '#FFCC00', '#33FF00', '#00FF99',
					'#00FFFF', '#0066FF', '#3300FF', '#CC00FF', '#FF00CC',
					'#FF0066', '#FF5733', '#33FF57', '#3357FF', '#F033FF',
					'#ff557f', '#ffffff', '#aa0000', '#aa557f'
				],
				selectedColor: '#000000',
				brushSize: 5,
				ctx: null,
				isDrawing: false,
				lastX: 0,
				lastY: 0,
				tempFilePath: '',
				startTime: null,
				usedTime: null
			}
		},
		onReady() {
			//开始计时
			this.startTime = Date.now()
			this.initCanvas();
		},
		methods: {
			initCanvas() {
				this.ctx = uni.createCanvasContext('drawingCanvas', this);

				// 1️⃣ 设置白色背景，避免透明图
				this.ctx.setFillStyle('#ffffff');
				this.ctx.fillRect(0, 0, 600, 500); // 你绘图区域的宽高（单位：px，不是 rpx）

				// 2️⃣ 初始化画笔样式
				this.ctx.setStrokeStyle(this.selectedColor);
				this.ctx.setLineWidth(this.brushSize);
				this.ctx.setLineCap('round');
				this.ctx.setLineJoin('round');

				// 3️⃣ 一定要 draw 一下才会真正画到 canvas 上
				this.ctx.draw();
			},
			handleTouchStart(e) {
				this.isDrawing = true;
				this.lastX = e.touches[0].x;
				this.lastY = e.touches[0].y;
			},
			handleTouchMove(e) {
				if (!this.isDrawing) return;

				const x = e.touches[0].x;
				const y = e.touches[0].y;

				this.ctx.beginPath();
				this.ctx.moveTo(this.lastX, this.lastY);
				this.ctx.lineTo(x, y);
				this.ctx.stroke();
				this.ctx.draw(true);

				this.lastX = x;
				this.lastY = y;
			},
			handleTouchEnd() {
				this.isDrawing = false;
			},
			selectColor(color) {
				this.selectedColor = color;
				this.ctx.setStrokeStyle(color);
			},
			clearCanvas() {
				this.ctx.clearRect(0, 0, 600, 400);
				this.ctx.draw(true);
			},
			submitDrawing() {
				// 第一步：canvas 转临时文件路径
				uni.canvasToTempFilePath({
					canvasId: 'drawingCanvas', // 你的 canvas ID
					success: (res) => {
						this.tempFilePath = res.tempFilePath;
						console.log('临时图片路径:', this.tempFilePath);
						// 上传到服务器
						this.uploadToServer(this.tempFilePath);
					},
					fail: (err) => {
						console.error('canvas 转图片失败:', err);
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						});
					}
				}, this);
			},

			uploadToServer(filePath) {
				const token = uni.getStorageSync('token'); // 直接取本地缓存 token
				uni.uploadFile({
					url: 'http://ip-pppoe-liaoning-07.xyzy.eu.org:5532/common/upload', // 你后端的上传地址
					filePath: filePath,
					name: 'file', // 后端接收字段名
					header: {
						'Authorization': 'wx' + token, // 如果后端要求 Authorization
					},
					success: (uploadRes) => {
						console.log('上传成功:', uploadRes);
						const data = JSON.parse(uploadRes.data); // 若返回 JSON 字符串
						uni.showToast({
							title: '上传成功',
							icon: 'success'
						});
						const result = JSON.parse(uploadRes.data);
						console.log(result);
						const aiUrl = result.url
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						});
						
						if (this.startTime) {
							console.log('111')
							const startTime1 = (typeof this.startTime === 'number' && this.startTime < 1e12) ?
								this.startTime * 1000 :
								this.startTime;
							const endTime = Date.now();
							let durationSeconds = Math.floor((endTime - startTime1) / 1000);
							if (durationSeconds < 0 || isNaN(durationSeconds)) durationSeconds = 0;
							this.usedTime = this.formatDuration(durationSeconds);
						} else {
							console.log(this.startTime)
							console.log('222')
							this.usedTime = '未记录';
							console.log('⚠️ startTime 获取失败');
						}
						
						const pages = getCurrentPages();
						const prevPage = pages[pages.length - 2];
						prevPage.$vm.imageUrl = filePath;
						prevPage.$vm.aiUrl = aiUrl;
						prevPage.$vm.usedTime = this.usedTime;
						uni.navigateBack();
					},
					fail: (err) => {
						console.error('上传失败:', err);
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						});
					}
				});
			},
			handleSliderChange(e) {
				this.brushSize = e.detail.value;
				this.ctx.setLineWidth(this.brushSize);
			},
			formatDuration(seconds) {
				// 把秒数格式化成几分几秒
				const m = Math.floor(seconds / 60)
				const s = seconds % 60
				return `${m}分${s}秒`
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		background-color: #fff;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.custom-nav-bar {
		padding: 20rpx 30rpx;
		background-color: rgb(248, 248, 248);
		color: white;
		text-align: center;
		padding-top: var(--status-bar-height);
		display: flex;
		align-items: center;
		position: relative;
	}



	.title-container {
		margin-top: -20rpx;
		flex: 1;
		text-align: center;
	}

	.custom-nav-bar .title {
		font-size: 35rpx;
		font-weight: bold;
		display: block;
		color: #000000;
	}

	.custom-nav-bar .subtitle {
		font-size: 25rpx;
		display: block;
		margin-top: 10rpx;
		color: #000000;
	}

	.tip {
		padding: 20rpx;
		background-color: #f8f8f8;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		color: #666;
		font-size: 28rpx;
	}

	.drawing-area {
		margin: 30rpx 30rpx 50rpx 30rpx;
		border: 2rpx solid #e4e7ed;
		border-radius: 12rpx;
		height: 500rpx;
		background-color: #fafafa;
	}

	.drawing-canvas {
		width: 100%;
		height: 100%;
	}

	.toolbar {
		margin: 0 30rpx;
		padding: 20rpx;
		background-color: #f8f8f8;
		border-radius: 12rpx;
	}

	.color-picker {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		margin-bottom: 30rpx;
	}

	.color-option {
		width: 36rpx;
		height: 36rpx;
		border-radius: 50%;
		margin: 8rpx;
	}

	.brush-size {
		display: flex;
		flex-direction: column;
		font-size: 28rpx;
		color: #666;
		margin-top: 20rpx;

		text {
			margin-bottom: 15rpx;
		}
	}

	.action-buttons {
		margin: 40rpx 30rpx 30rpx;
		display: flex;
		justify-content: center;

		.clear-btn {
			margin-right: 40rpx;
		}

		.submit-btn {
			margin-left: 40rpx;
		}

		.button-gap {
			width: 40rpx;
		}

		.u-button {
			flex: none;
			width: 250rpx;
		}
	}
</style>